package com.zhkj.shixi.tvfilemanager;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.zhkj.shixi.tvfilemanager.Interface.StartAction;
import com.zhkj.shixi.tvfilemanager.base.BaseFragment;
import com.zhkj.shixi.tvfilemanager.utils.USBUtil;
import com.zhkj.shixi.tvfilemanager.view.GrideViewPager;
import com.zhkj.shixi.tvfilemanager.view.ListViewPager;
import com.zhkj.shixi.tvfilemanager.view.ViewDataFlush;

import java.io.File;
import java.util.List;

import static com.zhkj.shixi.tvfilemanager.StaticClasses.deviceList;
import static com.zhkj.shixi.tvfilemanager.StaticClasses.fileManager;

public class FileListActivity extends FragmentActivity implements StartAction,View.OnClickListener,TextWatcher{
    private static final String TAG = "FileListActivity";
    public static final int GRID_VIEW_TYPE = 0;
    public static final int LIST_VIEW_TYPE = 1;
    private TextView mReturnText;

    private ListView mListView;
    private Button mChoice;
    private Button mEdit;
    private Button mArray;
    private Button mDisplayModel;
    private ImageView mClearText;
    private FileMenuCtrl mFileMenuCtrl;
    private EditText mEditText;
    private View mMenu;


    public static boolean isGridView = true;
    private Button mBtnSelectShow;
    private GrideViewPager mGridViewPager;
    private ListViewPager mListViewPager;
    private BaseFragment mBaseFragment;



    private boolean isSlctStat = false;
    public static boolean searchMode = false;
    private void init() {

        mMenu = findViewById(R.id.menu);
        mReturnText = findViewById(R.id.returnText);
//        mListView = findViewById(R.id.listView);
        mChoice = findViewById(R.id.choice);
        mEdit = findViewById(R.id.edit);
        mArray = findViewById(R.id.array);
        mDisplayModel = findViewById(R.id.displayModel);
        mClearText = findViewById(R.id.clearText);
        mEditText = findViewById(R.id.editText);
        mChoice.setOnClickListener(this);
        mEdit.setOnClickListener(this);
        mArray.setOnClickListener(this);
        mDisplayModel.setOnClickListener(this);
        mClearText.setOnClickListener(this);
        mEditText.addTextChangedListener(this);

        mFileMenuCtrl = new FileMenuCtrl(this);
        //初始化网格和列表数据
        mGridViewPager = new GrideViewPager(this,R.layout.grid_view_pager);
        mListViewPager = new ListViewPager(this,R.layout.list_view_pager);

    }

    @Override
    protected void onResume() {
        deviceList.clear();
        for(Object path : USBUtil.getUSBPaths(this)){
            File file = new File((String)path);
            deviceList.add(file);
        }
        if(deviceList.isEmpty()){
            this.finish();
        }
        super.onResume();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.tv_file_manager_list);
        init();
        mFileMenuCtrl = new FileMenuCtrl(this);

        mBtnSelectShow = (Button) findViewById(R.id.displayModel);
        mBtnSelectShow.setOnClickListener(this);

        if(deviceList.isEmpty()){
            List device = USBUtil.getUSBPaths(this);
            if(!device.isEmpty()){
                for(Object de :device){
                    File file = new File((String)de);
                    deviceList.add(file);
                }
            }
        }

        if (FileManager.MUSIC_TYPE  == fileManager.getType()) {
            mReturnText.setText("音频");
            //TODO 插入到网格或列表布局
//            setViewModelFragment(GRID_VIEW_TYPE);
            setViewModelFragment(GRID_VIEW_TYPE);
        }else if (FileManager.VIDEO_TYPE == fileManager.getType()) {
            mReturnText.setText("视频");
            //TODO 插入到网格或列表布局
        }else {
            mReturnText.setText("图片");
            //TODO 插入到网格或列表布局
        }


        if(isGridView) {
            setViewModelFragment(LIST_VIEW_TYPE);
            setViewModelFragment(GRID_VIEW_TYPE);
        }else{
            setViewModelFragment(GRID_VIEW_TYPE);
            setViewModelFragment(LIST_VIEW_TYPE);
        }

//        initViews();



    }


    @Override
    public void startAction(Context context) {
        Intent intent = new Intent(context, FileListActivity.class);
        context.startActivity(intent);
    }

    @Override
    //TODO 功能菜单
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.choice:

                isSlctStat = !isSlctStat;
                if (isSlctStat) {
                    mChoice.setBackgroundResource(R.drawable.video_usb_button_pressed);
                }else {
                    mChoice.setBackgroundResource(R.drawable.video_usb_button_selector);
                    ViewDataFlush.flushData(FileManager.getTypeFiles(fileManager.getCurrentURL(),fileManager.getType()),isGridView);
                    mFileMenuCtrl.removeAllFile();
                    GrideViewPager.bMap.clear();
                }
                break;
            case R.id.edit:
                showMyDialog(R.layout.edit_dialog);
                break;
            case R.id.array:
                showMyDialog(R.layout.sort_dialog);
                break;
            case R.id.displayModel:
                isGridView=!isGridView;
                if(!isGridView) {
                    setViewModelFragment(LIST_VIEW_TYPE);
                    ViewDataFlush.flushData(GrideViewPager.fileList,isGridView);
                    mFileMenuCtrl.removeAllFile();
                    GrideViewPager.bMap.clear();
                }else{
                    setViewModelFragment(GRID_VIEW_TYPE);
                    ViewDataFlush.flushData(GrideViewPager.fileList,isGridView);
                    mFileMenuCtrl.removeAllFile();
                    GrideViewPager.bMap.clear();
                }
                break;
            case R.id.clearText:
                mEditText.setText("");

                break;

        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (fileManager.getCurrentURL() != null && keyCode == KeyEvent.KEYCODE_MENU){
            Log.e("onKey ", fileManager.getCurrentURL());
            if (mMenu.getVisibility() == View.INVISIBLE) {
                mMenu.setVisibility(View.VISIBLE);
            }else {
                mMenu.setVisibility(View.INVISIBLE);
            }

        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 显示编辑和排序窗口
     * @author linjing
     * @param type
     */
    private void showMyDialog(int type){
        View view = LayoutInflater.from(this).inflate(type,null,false);
        final AlertDialog dialog = new AlertDialog.Builder(this).setView(view).create();
        if (type == R.layout.edit_dialog ){
            View DeleteFile = view.findViewById(R.id.deleteFile);
            View CopyFile = view.findViewById(R.id.copyFile);
            View PasteFile = view.findViewById(R.id.pasteFile);
            View RenameFile = view.findViewById(R.id.renameFile);
            DeleteFile.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //TODO 删除功能
                    mFileMenuCtrl.deleteFile();
                    GrideViewPager.fileList = FileManager.getTypeFiles(fileManager.getCurrentURL(),fileManager.getType());
                    ViewDataFlush.flushData(GrideViewPager.fileList,isGridView);
                    mFileMenuCtrl.removeAllFile();
                    Toast.makeText(FileListActivity.this, "删除", Toast.LENGTH_SHORT).show();
                    dialog.dismiss();
                }
            });

            CopyFile.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //TODO 复制功能
                    mFileMenuCtrl.copyFile();
                    Toast.makeText(FileListActivity.this, "复制", Toast.LENGTH_SHORT).show();
                    dialog.dismiss();
                }
            });

            PasteFile.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //TODO 粘帖功能
                    mFileMenuCtrl.pasteFile();
                    GrideViewPager.fileList = FileManager.getTypeFiles(fileManager.getCurrentURL(),fileManager.getType());
                    ViewDataFlush.flushData(GrideViewPager.fileList,isGridView);
                    mFileMenuCtrl.removeAllFile();
                    Toast.makeText(FileListActivity.this, "粘帖", Toast.LENGTH_SHORT).show();
                    dialog.dismiss();
                }
            });

            RenameFile.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //TODO 重命名功能
                    mFileMenuCtrl.renameDialog();
//                    GrideViewPager.fileList = FileManager.getTypeFiles(fileManager.getCurrentURL(),fileManager.getType());
//                    ViewDataFlush.flushData(GrideViewPager.fileList,isGridView);
//                    mFileMenuCtrl.removeAllFile();
                    Toast.makeText(FileListActivity.this, "重命名", Toast.LENGTH_SHORT).show();
                    dialog.dismiss();
                }
            });
        }else {
            View SortByName = view.findViewById(R.id.sortByName);
            View SortBySize = view.findViewById(R.id.sortBySize);
            View SortByDate = view.findViewById(R.id.sortByDate);
            SortByName.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //TODO 按名称排序功能
                    List<File> list = SortFiles.sortFiles(fileManager.getCurrentURL(), SortFiles.SORT_BY_NAME);
                    GrideViewPager.fileList = list;
                    ViewDataFlush.flushData(GrideViewPager.fileList,isGridView);
                    mFileMenuCtrl.removeAllFile();
                    dialog.dismiss();
                    Toast.makeText(FileListActivity.this, "按名称排序功能", Toast.LENGTH_SHORT).show();
                }
            });
            SortBySize.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //TODO 按大小排序功能
                    List<File> list = SortFiles.sortFiles(fileManager.getCurrentURL(), SortFiles.SORT_BY_SIZE);
                    GrideViewPager.fileList = list;
                    ViewDataFlush.flushData(GrideViewPager.fileList,isGridView);
                    mFileMenuCtrl.removeAllFile();
                    dialog.dismiss();
                    Toast.makeText(FileListActivity.this, "按大小排序功能", Toast.LENGTH_SHORT).show();
                }
            });
            SortByDate.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //TODO 按修改日期排序功能
                    List<File> list = SortFiles.sortFiles(fileManager.getCurrentURL(), SortFiles.SORT_BY_DATE);
                    GrideViewPager.fileList = list;
                    ViewDataFlush.flushData(GrideViewPager.fileList,isGridView);
                    mFileMenuCtrl.removeAllFile();
                    dialog.dismiss();
                    Toast.makeText(FileListActivity.this, "按修改日期排序功能", Toast.LENGTH_SHORT).show();
                }
            });
        }
        dialog.show();
        //此处设置位置窗体大小，我这里设置为了手机屏幕宽度的3/10  注意一定要在show方法调用后再写设置窗口大小的代码，否则不起效果会
        dialog.getWindow().setLayout((FileManager.getScreenWidth(this)/10*3), LinearLayout.LayoutParams.WRAP_CONTENT);
    }

    @Override
    public void onBackPressed() {
        mFileMenuCtrl.removeAllFile();
        GrideViewPager.bMap.clear();
        if(fileManager.getCurrentURL() == null)
        {
            super.onBackPressed();
            return;
        }
        if(searchMode) {
            GrideViewPager.fileList=FileManager.getTypeFiles(fileManager.getCurrentURL(),fileManager.getType());
            ViewDataFlush.flushData(GrideViewPager.fileList,isGridView);
            mFileMenuCtrl.removeAllFile();
            mEditText.setText("");
            searchMode=false;
            return;
        }
        File file = new File(fileManager.getCurrentURL());
        if (file.getAbsolutePath().equals(deviceList.get(fileManager.getmUSB()).getAbsolutePath())){
            Log.w("curl1",fileManager.getCurrentURL());
            fileManager.setCurrentURL(null);
            isSlctStat = false;
            mChoice.setBackgroundResource(R.drawable.video_usb_button_selector);
            mMenu.setVisibility(View.INVISIBLE);
            GrideViewPager.fileList=deviceList;
            ViewDataFlush.flushData(GrideViewPager.fileList,isGridView);
            mFileMenuCtrl.removeAllFile();

            mReturnText.setText(mReturnText.getText().toString().substring(0,2));

        }
        else
        {
            fileManager.setCurrentURL(file.getParent());
            GrideViewPager.fileList = FileManager.getTypeFiles(fileManager.getCurrentURL(),fileManager.getType());
            ViewDataFlush.flushData(GrideViewPager.fileList,isGridView);
            mFileMenuCtrl.removeAllFile();
            Log.w("curl2",fileManager.getCurrentURL());
        }/*else {
            super.onBackPressed();
            Log.w("curl3",fileManager.getCurrentURL());
        }*/
    }

    /**
     * 网格和列表显示与切换
     * @param position 传入GRID_VIEW_TYP网格显示，LIST_VIEW_TYPE列表显示
     */
    private void setViewModelFragment(int position){

        mBaseFragment = new BaseFragment();
        //添加网格播放列表页面
        mBaseFragment.add(mGridViewPager);
        //添加列表播放列表页面
        mBaseFragment.add(mListViewPager);
        //设置列表位置
        mBaseFragment.setmPosition(position);
        //获取管理器
        android.support.v4.app.FragmentManager mFragmentManager = getSupportFragmentManager();
        //启动事物
        FragmentTransaction mFragmentTransaction = mFragmentManager.beginTransaction();
        //替换
        mFragmentTransaction.replace(R.id.gird_list_view,mBaseFragment);
        //提交事务
        mFragmentTransaction.commit();
    }

    public FileMenuCtrl getFileMenuCtrl() {
        return mFileMenuCtrl;
    }

    public boolean isSlctStat() {
        return isSlctStat;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        //如果长度为0
        if (s.length() == 0) {
            //隐藏“删除”图片
            mClearText.setVisibility(View.GONE);
        } else {//长度不为0
            //显示“删除图片”
            mClearText.setVisibility(View.VISIBLE);
            mClearText.setFocusable(true);
            //显示ListView

            showListView();
        }

    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    private void showListView() {


//        final String rootUrl =deviceList.get(fileManager.getmUSB()).getPath().trim();
//        fileSearch.fileFilterF(rootUrl);
        String text = mEditText.getText().toString();
        FileSearch fileSearch = mGridViewPager.getFileSearch();
        Log.i(TAG, "showListView: "+mGridViewPager.ismIsOver());
        if (mGridViewPager.ismIsOver()){
            GrideViewPager.fileList=fileSearch.fileSearch(text);
            Log.i(TAG, "showListView: "+fileSearch.getAllMediaFiles());
            ViewDataFlush.flushData(GrideViewPager.fileList,isGridView);
            mFileMenuCtrl.removeAllFile();
            searchMode=true;

        }else {
            Log.i(TAG, "showListView:dddddddddd ");
        }


    }

}
